package com.miyake.server;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.google.appengine.repackaged.com.google.common.util.Base64;
import com.google.appengine.repackaged.com.google.common.util.Base64DecoderException;

public class MyBase64 {
	public static double[] decodeToDouble(String data, int size) {
		byte[] ba = null;
		try {
			ba = Base64.decode(data);
		} catch (Base64DecoderException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new ByteArrayInputStream(ba));
		} catch (IOException e) {
			e.printStackTrace();
		}
		double[] ret = new double[Integer.valueOf(size)];
		for (int i = 0; i < ret.length; i++) {
			try {
				ret[i] = ois.readDouble();
			} catch (IOException e) {
				break;
			}
		}
		return ret;
	}
	
	public static String[] decodeToString(String data, int size) {
		byte[] ba = null;
		try {
			ba = Base64.decode(data);
		} catch (Base64DecoderException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new ByteArrayInputStream(ba));
		} catch (IOException e) {
			e.printStackTrace();
		}
		String[] ret = new String[Integer.valueOf(size)];
		for (int i = 0; i < ret.length; i++) {
			try {
				ret[i] = String.valueOf(ois.readDouble());
			} catch (IOException e) {
				break;
			}
		}
		return ret;
	}
	
	public static String encode(Double[] d) {

		String ret = "";
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			ObjectOutputStream oos = new ObjectOutputStream(bos);
			for (int i = 0; i < d.length; i++) {
				oos.writeDouble(d[i]);
			}
			oos.flush();
			
			ret = Base64.encode(bos.toByteArray());

			
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			try {
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}
}
